package com.itheima.aop;

import com.itheima.pojo.LogInfo;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class ControllerAop {

    //设置切入点，@Pointcut注解要求配置在方法上方
    @Pointcut("execution(* com.itheima.controller.Controller.*(..))")
    private void pt(){}

    @Autowired
    private HttpServletRequest request;

    private Date startTime ;
    private Date endTime ;
    private long userId ;

    @Before("pt()")
    public void before() {
        startTime = new Date();//获得开始时间
    }

    @After("pt()")
    private void after(){
        //1.构架出日志对象
        //2.存储到mysql中
        LogInfo lg = new LogInfo();
        String uri = request.getRequestURI(); //请求的地址
        String remoteAddr = request.getRemoteAddr(); //获得请求的ip地址
        endTime = new Date();//获得结束时间
        lg.setIp(remoteAddr);
        lg.setMethodStart(startTime);
        lg.setMethodEnd(endTime);
        lg.setMethod(uri);
        lg.setMethodTime(endTime.getTime()-startTime.getTime());
        //存储到mysql
        System.out.println("info日志信息....."+lg);
    }
}
